package com.lz.gmall.web.controller;

import com.lz.gamll.feign.cart.AddCartFeignClient;
import com.lz.gamll.feign.product.SkuDetailFeignClient;
import com.lz.gmall.cart.vo.AddCartVo;
import com.lz.gmall.product.entity.SkuInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.ConcurrentHashMap;


@Controller
@Slf4j
public class CartController {

    @Autowired
    private AddCartFeignClient addCartFeignClient;

    //public static final ConcurrentHashMap<Thread , HttpServletRequest> hashMap = new ConcurrentHashMap() ;
    //public static final ThreadLocal<HttpServletRequest> threadLocal = new ThreadLocal<>() ;

    /**
     * 前端点击加入购物车，进入web-all中经过远程调用去完成商品的添加
     * 用户id和用户临时id是经过透传 传递过来的，是在请求头中，feign远程调用会丢失请求头
     * 采用springMVC提供的RequestContextHolder进行feign的拦截器中进行处理，获取到request
     * @param skuId 用户id
     * @param skuNum  用户临时id
     * @param model 封装返回前端
     * @return
     */
    @GetMapping("/addCart.html")
    public String addCart(@RequestParam("skuId") Long skuId,
                          @RequestParam("skuNum") Integer skuNum,
                          //@RequestHeader(value = "userId",required = false)String userId,
                          //@RequestHeader(value = "userTempId",required = false)String userTempId,
                          Model model){
        //log.info("skuId:{},skuNum:{},userId:{},userTempId:{}",skuId,skuNum,userId,userTempId);

        //hashMap.put(Thread.currentThread(),request);
        //threadLocal.set(request);

        //远程调用service-cart微服务进行添加购物车
        AddCartVo addCartVo = addCartFeignClient.addCart(skuId, skuNum).getData();

        model.addAttribute("skuInfo",addCartVo.getSkuInfo());
        model.addAttribute("skuNum",addCartVo.getSkuNum());

        return "cart/addCart";
    }

    /**
     * 前端访问进入购物车详情页
     * @return
     */
    @GetMapping("/cart.html")
    public String getCartList(){
        return "cart/index";
    }
}
